<template>
  <div class="app-container">
    <div class="filter-container flex-between--center">
      <span class="pageTitle">{{ this.title }}</span>
      <div>
        <el-button  type="primary" icon="el-icon-d-arrow-left" size="small" @click="tabActive = 0" v-show="tabActive == 1">上一步</el-button>
        <el-button  type="primary" icon="el-icon-circle-plus" size="small" :disabled="saveDisabled" @click="clickToSave">保存</el-button>
        <el-button  type="primary" icon="el-icon-delete" size="small" @click="clickToCancel">取消</el-button>
        <el-button  type="primary" icon="el-icon-d-arrow-right" size="small" @click="tabActive = 1" v-show="tabActive == 0">下一步</el-button>
      </div>
    </div>
    <div class="tabs">
      <span :class="tabActive?'':'active'" @click="clickTab(0)">1.商品信息</span>
      <span :class="tabActive?'active':''" @click="clickTab(1)">2.商品返利比例</span>
    </div>
    <div v-show="!tabActive">
      <el-form class="form" :rules="productRules" label-position="top" label-width="80%" :model="product" ref="product">
        <div>
          <el-form-item prop="nameCn" label="中文商品名称" class="form-item--inline">
            <el-input v-model="product.nameCn" placeholder="请输入中文商品名称/最多40个字" style="width:90%" :maxlength="40" size="medium"></el-input>
          </el-form-item>
          <el-form-item prop="nameEn" label="英文商品名称" class="form-item--inline">
            <el-input v-model="product.nameEn" placeholder="请输入英文商品名称/最多120个字符" style="width:90%" :maxlength="120" size="medium"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="productsDescCn" label="中文商品宣传文案" class="form-item--inline">
            <el-input v-model="product.productsDescCn" placeholder="请输入中文商品宣传文案/最多25个字" style="width:90%" :maxlength="25" size="medium"></el-input>
          </el-form-item>
          <el-form-item prop="productsDescEn" label="英文商品宣传文案" class="form-item--inline">
            <el-input v-model="product.productsDescEn" placeholder="请输入英文商品宣传文案/最多100个字符" style="width:90%" :maxlength="100" size="medium"></el-input>
          </el-form-item>
        </div>
        <el-form-item prop="category" label="中/英文商品前台分组">
          <el-select v-model="selectedOptionsFront" @change="handleOptionsFront" placeholder="请选择中/英文商品前台分组" multiple filterable clearable style="width: 45%">
            <el-option-group
              v-for="group in frontCategoryOptions"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group.children"
                :key="item.value"
                :label="`${group.label}/${item.label}`"
                :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item prop="categoryManager" label="商品后台分组">
          <el-cascader style="width: 45%"
            clearable
            filterable
            placeholder="请选择商品后台分组"
            @change="handleOptionsBack"
            :options="backCategoryOptions"
            v-model="selectedOptionsBack"
            class="normalOperatorBox"
            size="medium">
          </el-cascader>
        </el-form-item>

        <!-- 图片 -->
        <div>
          <el-form-item prop="productsFormCn" label="中文商品列表主图（建议尺寸：710*270像素以上，大小2M以下；支持jpg、jpeg、png；只能上传一张图片）" class="form-item--inline">
            <el-upload
              :headers="headers"
              :limit="1"
              class="avatar-uploader"
              :multiple="false"
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsFormCn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'productsFormCn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'productsFormCn') }"
              :before-upload="handleBeforeUpload"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item prop="productsFormEn" label="英文商品列表主图（建议尺寸：710*270像素以上，大小2M以下；支持jpg、jpeg、png；只能上传一张图片）" class="form-item--inline">
            <el-upload
              :headers="headers"
              :limit="1"
              class="avatar-uploader"
              :multiple="false"
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsFormEn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'productsFormEn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'productsFormEn') }"
              :before-upload="handleBeforeUpload"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item prop="productsRotationCn" label="中文商品图片（大小2M以下；支持jpg、jpeg、png；至少上传一张图片，最多上传6张图片）">
          拖拽开关：<el-switch v-model="upload.swiperDragCn" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          <div style="position:relative">
            <el-upload
              :headers="headers"
              multiple
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsRotationCn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'swiperCn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'swiperCn') }"
              :before-upload="handleBeforeUpload"
              :limit="6"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
            <draggable v-model="upload.productsRotationCn" class="draggable" v-show="upload.swiperDragCn">
              <transition-group>
                <div v-for="element in upload.productsRotationCn" :key="element.url" class="draggable__item">
                  <img :src="element.url" alt="" class="width--full">
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-form-item>
        <el-form-item prop="productsRotationEn" label="英文商品图片（大小2M以下；支持jpg、jpeg、png；至少上传一张图片，最多上传6张图片）">
          拖拽开关：<el-switch v-model="upload.swiperDragEn" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          <div style="position:relative">
            <el-upload
              :headers="headers"
              multiple
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsRotationEn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'swiperEn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'swiperEn') }"
              :before-upload="handleBeforeUpload"
              :limit="6"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
            <draggable v-model="upload.productsRotationEn" class="draggable" v-show="upload.swiperDragEn">
              <transition-group>
                <div v-for="element in upload.productsRotationEn" :key="element.url" class="draggable__item">
                  <img :src="element.url" alt="" class="width--full">
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-form-item>
        <el-form-item prop="images" label="中文详情图片（大小2M以下；支持jpg、jpeg、png，最多上传20张图片）" >
          拖拽开关：<el-switch v-model="upload.detailDragCn" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          <div style="position:relative">
            <el-upload
              :headers="headers"
              multiple
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsDetailCn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'detailCn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'detailCn') }"
              :before-upload="handleBeforeUpload"
              :limit="20"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
            <draggable v-model="upload.productsDetailCn" class="draggable" v-show="upload.detailDragCn">
              <transition-group>
                <div v-for="element in upload.productsDetailCn" :key="element.url" class="draggable__item">
                  <img :src="element.url" alt="" class="width--full">
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-form-item>
        <el-form-item prop="images" label="英文详情图片（大小2M以下；支持jpg、jpeg、png，最多上传20张图片）" >
          拖拽开关：<el-switch v-model="upload.detailDragEn" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          <div style="position:relative">
            <el-upload
              :headers="headers"
              multiple
              :name="uploadFileName"
              :action="uploadFileUrl"
              :file-list="upload.productsDetailEn"
              :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'detailEn') }"
              :on-success="(res, file, fileList) => { return handleUploadSuccess(res, file, fileList, 'detailEn') }"
              :before-upload="handleBeforeUpload"
              :limit="20"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
            <draggable v-model="upload.productsDetailEn" class="draggable" v-show="upload.detailDragEn">
              <transition-group>
                <div v-for="element in upload.productsDetailEn" :key="element.url" class="draggable__item">
                  <img :src="element.url" alt="" class="width--full">
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-form-item>

        <el-form-item prop="price" label="原价">
          <el-input-number v-model="minPrice" :disabled="formattedSkus.length !== 0" :min="0" :max="9999999" size="medium" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item prop="priceVip" label="VIP售价">
          <el-input-number v-model="minPriceVip" :disabled="formattedSkus.length !== 0" :min="0" :max="9999999" size="medium" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item prop="stock" label="商品库存">
          <el-input-number v-model="totalStock" :disabled="formattedSkus.length !== 0" :min="0" :max="99999" size="medium" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item prop="weight" label="商品质量（单位：kg）">
          <el-input-number v-model="product.weight" :min="0" :max="99999" size="medium" :precision="0"></el-input-number>
        </el-form-item>
        <!-- 运费 -->
        <div>
          <el-form-item prop="freightFlag" label="运费计算方式" class="inline">
            <el-radio-group v-model="product.freightFlag" size="medium">
              <el-radio :label="0" border>卖家承担运费</el-radio>
              <el-radio :label="2" border>买家承担运费</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="freightId" label="运费模板：" v-show="product.freightFlag == 2" class="form-item--inline" style="margin-left:20px">
            <el-select v-model="product.freightId" size="medium" style="width:400px;" placeholder="请选择运费模板">
              <el-option v-for="(item, index) in freightList" :key="index" :label="item.templateName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 添加商品规格 -->
        <el-form :rules="attributesRules" label-position="top" label-width="80%" :model="attributesFrom" ref="attributesFrom">
          <el-form-item prop="inputingSpecNameCn" label="商品规格" class="inline">
            <el-input
              v-model="attributesFrom.inputingSpecNameCn"
              placeholder="输入中文规格值"
              @keyup.enter.native="clickToAddSpec" :maxlength="8" size="medium"></el-input>
          </el-form-item>
          <el-form-item prop="inputingSpecNameEn" label="" class="inline" style="margin-right:10px">
            <el-input
              v-model="attributesFrom.inputingSpecNameEn"
              placeholder="输入英文规格值"
              @keyup.enter.native="clickToAddSpec" :maxlength="8" style="margin-left:10px" size="medium"></el-input>
          </el-form-item>
          <el-button plain type="primary" @click="clickToAddSpec" class="verticalButton" icon="el-icon-plus" size="medium">添加规格</el-button>
          <el-button plain type="warning" @click="clickToCancelAddSpec" class="verticalButton" icon="el-icon-delete" size="medium">取消</el-button>
        </el-form>
        <!-- 添加属性标签 -->
        <el-table :data="skuProps" border size="medium">
          <el-table-column label="中/英文规格名称" min-width="20%">
            <template slot-scope="scope">
              <span>{{scope.row.nameCn}}/{{scope.row.nameEn}}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格属性（中/英文）" min-width="60%">
            <template slot-scope="scope">
              <el-tag
                style="margin-right:5px"
                :key="index"
                v-for="(tag, index) in scope.row.values"
                closable
                :disable-transitions="false"
                @close="clickToRemoveAttribute(index, scope.$index)">
                {{tag.nameCn}}/{{tag.nameEn}}
              </el-tag>
              <div v-if="tagInputVisible && scope.$index === activeTag">
                <el-form :rules="specRules" label-position="top" label-width="80%" :model="specFrom" ref="specFrom">
                  <el-form-item prop="tagInputValueCn" label="" class="inline input-new-tag">
                    <el-input
                      placeholder="中文规格"
                      v-model="specFrom.tagInputValueCn"
                      size="small"
                      @keyup.enter.native="handleConfirmTagInput(scope.$index)"
                      :maxlength="12"
                      @blur="handleConfirmTagInput(scope.$index)">
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="tagInputValueEn" label="" class="inline input-new-tag">
                    <el-input
                      placeholder="英文规格"
                      v-model="specFrom.tagInputValueEn"
                      size="small"
                      @keyup.enter.native="handleConfirmTagInput(scope.$index)"
                      :maxlength="12"
                      @blur="handleConfirmTagInput(scope.$index)">
                    </el-input>
                  </el-form-item>
                  <el-button class="button-new-tag" size="mini" type="primary" @click="handleConfirmTagInput(scope.$index)">保存</el-button>
                </el-form>
              </div>
              <el-button v-else class="button-new-tag" size="small" @click="clickToShowTagInput(scope.$index)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="clickToDeleteSku(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- sku排列组合 -->
        <el-form-item prop="sku" style="margin-top:20px">
          <el-table border :data="formattedSkus" class="table">
            <el-table-column
              v-for="(spec, index) in skuProps.filter(((element) => { return element.values.length > 0 }))"
              :key="index"
              :label="`${spec.nameCn}/${spec.nameEn}`">
              <template slot-scope="scope">
                <span>
                  {{ getSkuAttribute(scope.row.combination, spec.nameCn) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="原价格" min-width="150px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.price" :min="0" :max="9999999" size="small" :precision="2" style="width:100%"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="VIP价格" min-width="150px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.priceVip" :min="0" :max="9999999" size="small" :precision="2" style="width:100%"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="库存" min-width="150px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.stock" :min="0" :max="99999" size="small" :precision="0" style="width:100%"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="规格图片" width="170px">
              {{uploadFileName}}
              <template slot-scope="scope">
                <el-upload
                  :headers="headers"
                  class="avatar-uploader"
                  :name="uploadFileName"
                  :action="uploadFileUrl"
                  :file-list="scope.row.fileList"
                  :on-remove="(file, fileList) => { return handleUploaderRemove(file, fileList, 'skuUploader', scope.$index) }"
                  :on-success="(response, file, fileList) => { return handleUploaderSuccess(response, file, fileList, 'skuUploader', scope.$index) }"
                  :before-upload="(file) => {return handleBeforeUpload(file, '4')}"
                  :limit="1"
                  list-type="picture-card">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="tabActive === 1" style="margin: 0 auto;width:60%">
      <el-form class="form">
        <el-form-item label="">
          <!-- <span class="title">商品返利比例</span> -->
          <!-- <span class="title" style="margin-left:20px">商品返利系数</span> -->
        </el-form-item>
        <el-form-item :label="`${index == 0 ? '自购': 'S0~S6'}：`" :label-width="formLabelWidth" v-for="(item, index) in product.productCommissions" :key="index">
          <el-input placeholder="请输入内容" size="medium" style="width:70%" v-model="item.rate">
            <i slot="suffix">%</i>
          </el-input>
          <!-- <el-input placeholder="请输入内容" size="medium" style="width:30%;margin-left:20px" v-if = "index" v-model="item.coefficient">
            <i slot="suffix">%</i>
          </el-input> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import {
  insertProduct,
  updateProduct,
  getListCategory,
  getProductDetail
} from '@/api/product'
import { getTemplateList } from '@/api/freightTemplate'

import { categoryFilter, arrayToString, stringToArray, divide, multiply } from '@/filter'
import draggable from 'vuedraggable'
export default {
  name: 'productEdit',
  components: {
    draggable
  },
  computed: {
    frontCategoryOptions () {
      return this.frontCategoryList.map(categoryFilter)
    },
    backCategoryOptions () {
      return this.backCategoryList.map(categoryFilter)
    },
    formattedSkus: {
      get: function () {
        const skuCombinations = this.multiplySpecs(
          this.skuProps.filter(element => {
            return element.values.length > 0
          })
        )
        const skus = skuCombinations.map((combination, index) => {
          // skuValue {颜色:蓝,尺寸:大}
          function generateSkuValue (skuCombination) {
            let skuValue = {
              valuesCn: '', // 颜色:蓝,尺寸:大
              valuesEn: ''
            }
            skuCombination.forEach((value, index, array) => {
              // skuValue.valuesCn[value.specCn] = value.attrCn
              // skuValue.valuesEn[value.specEn] = value.attrEn
              if (index) {
                skuValue.valuesCn += ','
                skuValue.valuesEn += ','
              }
              skuValue.valuesCn += `${value.specCn}:${value.attrCn}`
              skuValue.valuesEn += `${value.specEn}:${value.attrEn}`
            })
            return skuValue
          }
          function generatePropPath (skuCombination) {
            let propPath = ''
            skuCombination.forEach((value, index, array) => {
              const connectionSymbol = index === array.length - 1 ? '' : ';'
              propPath = propPath + value.pid + ':' + value.vid + connectionSymbol
            })
            return propPath
          }

          var skuValue = generateSkuValue(combination)
          let skuItem = {}
          this.product.listSku.some((sku, index) => {
            let valuesCn = ''
            let valuesEn = ''
            try {
              let valuesCnObj = JSON.parse(sku.valuesCn)
              let valuesEnObj = JSON.parse(sku.valuesEn)
              let i = 0
              for (let key in valuesCnObj) {
                if (i) {
                  valuesCn += ','
                }
                valuesCn += `${key}:${valuesCnObj[key]}`
                i++
              }
              i = 0
              for (let key in valuesEnObj) {
                if (i) {
                  valuesEn += ','
                }
                valuesEn += `${key}:${valuesEnObj[key]}`
                i++
              }
              if (skuValue.valuesCn === valuesCn && skuValue.valuesEn === valuesEn) {
                skuItem = sku
                return true
              }
            } catch (err) {
              console.log(err)
            }
          })
          // let sku = this.product.listSku[index] || {}
          let fileList = []
          if (skuItem.cover) {
            fileList.push({
              name: '',
              url: skuItem.cover
            })
          }
          return {
            combination: combination,
            id: skuItem.id || '',
            productsId: this.product.id,
            cover: skuItem.cover || '',
            fileList: fileList,
            price: divide(skuItem.price) || 0,
            priceVip: divide(skuItem.priceVip) || 0,
            stock: skuItem.stock || 0,
            valuesCn: skuValue.valuesCn,
            valuesEn: skuValue.valuesEn
            // value: JSON.stringify(skuValue),
            // propPath: propPath,
            // valuesCn: '',
            // valuesCn: ''
            // skuValue: skuValue
          }
        })
        // console.log('skus', skus)
        this.product.listSku = skus
        return skus
      },
      set: function (newValue) {
        this.product.listSku = newValue
      }
    },
    totalStock: {
      get: function () {
        if (this.formattedSkus.length === 0 || this.product.listSku.length === 0) {
          return this.product.stock
        } else {
          var stock = 0
          this.formattedSkus.forEach(sku => {
            stock = stock + parseInt(sku.stock)
          })
          this.product.stock = stock
          return stock
        }
      },
      set: function (value) {
        this.product.stock = value
      }
    },
    minPrice: {
      get: function () {
        if (
          this.formattedSkus.length === 0 ||
          this.product.listSku.length === 0
        ) {
          return this.product.price
        } else {
          let price = this.product.price
          if (this.formattedSkus.length > 0) {
            price = this.formattedSkus[0].price
            this.formattedSkus.forEach(item => {
              price = Math.min(price, item.price)
            })
          }
          this.product.price = price
          return price
        }
      },
      set: function (newValue) {
        this.product.price = newValue
      }
    },
    minPriceVip: {
      get: function () {
        if (
          this.formattedSkus.length === 0 ||
          this.product.listSku.length === 0
        ) {
          return this.product.priceVip
        } else {
          let priceVip = this.product.priceVip
          if (this.formattedSkus.length > 0) {
            priceVip = this.formattedSkus[0].priceVip
            this.formattedSkus.forEach(item => {
              priceVip = Math.min(priceVip, item.priceVip)
            })
          }
          this.product.priceVip = priceVip
          return priceVip
        }
      },
      set: function (newValue) {
        this.product.priceVip = newValue
      }
    }
  },
  data () {
    return {
      title: '新增商品',
      frontCategoryList: [],
      backCategoryList: [],
      selectedOptionsFront: [],
      selectedOptionsBack: [],
      freightList: [],
      formLabelWidth: '20%',
      tabActive: 0,
      freightFlagRadio: 0, // 运费方式：0卖家承担运费，1买家承担运费
      freightTypeRadio: 0, // 买家承担运费：0统一运费，1运费模板
      tagInputVisible: false, // 规格输入
      activeTag: undefined,
      skuProps: [],
      skuProps_: [
        {
          pid: null,
          nameCn: 'inputingSpecNameCn',
          nameEn: 'inputingSpecNameEn',
          values: [
            {
              vid: null,
              nameCn: 'inputValueCn',
              nameEn: 'inputValueEn',
              image: null
            }
          ]
        }
      ],
      tempProduct: {},
      product: {
        category: [], // productsCategory
        categoryManager: {}, // productsCategory
        coverCn: '', // 主图
        coverEn: '',
        freight: '',
        freightId: '',
        freightFlag: 0,
        id: 0,
        listSku: [], // productsSku
        nameCn: '',
        nameEn: '',
        price: 0,
        priceVip: 0,
        productsDescCn: '',
        productsDescEn: '',
        productsFormCn: '',
        productsFormEn: '',
        productsDetailCn: '',
        productsDetailEn: '',
        productCommissions: Array.from({ length: 2 }, (item, index) => ({
          id: null,
          productId: '',
          // coefficient: 0, // 系数
          memberLevel: index - 1, // 会员等级（-1-6）-1是自购无系数
          rate: '' // 佣金比例
        })),
        productsRotationCn: '', // 轮播图
        productsRotationEn: '',
        sales: 0,
        stock: 0,
        weight: 0
      },
      productsCategory: {
        id: 0
      },
      // productsSku: {
      //   cover: '',
      //   id: 0,
      //   price: 0,
      //   priceVip: 0,
      //   productsId: 0,
      //   stock: 0,
      //   valuesCn: '',
      //   valuesEn: ''
      // },
      productRules: {
        nameCn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('不能为空'))
            } else if (value.length > 40) {
              callback(new Error('中文商品名称最多40个字'))
            } else {
              callback()
            }
          }
        },
        nameEn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('不能为空'))
            } else if (value.length > 120) {
              callback(new Error('英文商品名称最多120个字符'))
            } else {
              callback()
            }
          }
        },
        productsDescCn: {
          required: false,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length > 25) {
              callback(new Error('中文商品宣传文案最多25个字'))
            } else {
              callback()
            }
          }
        },
        productsDescEn: {
          required: false,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length > 100) {
              callback(new Error('英文商品宣传文案最多100个字符'))
            } else {
              callback()
            }
          }
        },
        category: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('前台分组不能为空'))
            } else {
              callback()
            }
          }
        },
        categoryManager: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('后台分组不能为空'))
            } else {
              callback()
            }
          }
        },
        coverCn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('中文商品列表图不能为空'))
            } else {
              callback()
            }
          }
        },
        coverEn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('英文商品列表图不能为空'))
            } else {
              callback()
            }
          }
        },
        productsFormCn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('中文商品主图不能为空'))
            } else {
              callback()
            }
          }
        },
        productsFormEn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('英文商品主图不能为空'))
            } else {
              callback()
            }
          }
        },
        productsRotationCn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('至少上传一张中文商品图'))
            } else {
              callback()
            }
          }
        },
        productsRotationEn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('至少上传一张英文商品图'))
            } else {
              callback()
            }
          }
        },
        price: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value < 0 || value === '' || value === undefined) {
              callback(new Error('商品价格必须大于等于0'))
            } else {
              callback()
            }
          }
        },
        priceVip: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value < 0 || value === '' || value === undefined) {
              callback(new Error('商品VIP价格必须大于等于0'))
            } else {
              callback()
            }
          }
        },
        stock: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            callback()
          }
        },
        freightFlag: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            callback()
          }
        }
      },
      // 上传成功商品视频  商品介绍视频
      upload: {
        productsFormCn: [],
        productsFormEn: [],
        productsRotationCn: [],
        productsRotationEn: [],
        productsDetailCn: [],
        productsDetailEn: [],
        swiperDragCn: false,
        swiperDragEn: false,
        detailDragCn: false,
        detailDragEn: false
      },
      // activeUploader: '',
      uploadFileUrl: `${process.env.VUE_APP_UPLOAD_API}`,
      uploadFileName: `${process.env.VUE_APP_UPLOAD_NAME}`,
      headers: this.$headers,
      attributesFrom: {
        inputingSpecNameCn: '',
        inputingSpecNameEn: ''
      },
      attributesRules: {
        inputingSpecNameCn: {
          required: false,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('中文规格不能为空'))
            } else if (value.length > 8) {
              callback(new Error('中文规格最多8个字'))
            } else {
              callback()
            }
          }
        },
        inputingSpecNameEn: {
          required: false,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('英文规格不能为空'))
            } else if (value.length > 8) {
              callback(new Error('英文规格最多8个字符'))
            } else {
              callback()
            }
          }
        }
      },
      specFrom: {
        tagInputValueCn: '',
        tagInputValueEn: ''
      },
      specRules: {
        tagInputValueCn: {
          required: false,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('中文规格属性不能为空'))
            } else if (value.length > 12) {
              callback(new Error('中文规格属性最多12个字'))
            } else {
              callback()
            }
          }
        },
        tagInputValueEn: {
          required: false,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('英文规格不能为空'))
            } else if (value.length > 12) {
              callback(new Error('英文规格最多12个字符'))
            } else {
              callback()
            }
          }
        }
      },
      saveDisabled: false
    }
  },
  watch: {},
  mounted () {
    if (this.$route.query.productId) {
      this.product.id = this.$route.query.productId
      this.getProductDetail()
    }
    this.getCategory()
    this.getFreightList()
  },
  methods: {
    async getProductDetail () {
      let { data } = await getProductDetail({
        id: this.$route.query.productId
      })
      this.title = '编辑商品'
      this.product.id = data.id
      this.product.nameCn = data.nameCn
      this.product.nameEn = data.nameEn
      this.product.productsDescCn = data.productsDescCn
      this.product.productsDescEn = data.productsDescEn

      // 前台分组
      this.product.category = data.category
      this.selectedOptionsFront = data.category.map((item) => { return item.id })

      // 后台分组
      this.product.categoryManager = {
        id: data.categoryManager.id
      }
      this.selectedOptionsBack = [data.categoryManager.fid, data.categoryManager.id]

      // 图片
      this.product.coverCn = data.coverCn
      this.product.coverEn = data.coverEn
      this.product.productsFormCn = data.productsFormCn
      this.product.productsFormEn = data.productsFormEn
      this.upload.productsFormCn = stringToArray(data.productsFormCn, ',')
      this.upload.productsFormEn = stringToArray(data.productsFormEn, ',')

      this.upload.productsRotationCn = stringToArray(data.productsRotationCn, ',')
      this.upload.productsRotationEn = stringToArray(data.productsRotationEn, ',')
      this.upload.productsDetailCn = stringToArray(data.productsDetailCn, ',')
      this.upload.productsDetailEn = stringToArray(data.productsDetailEn, ',')

      this.product.price = divide(data.price)
      this.product.priceVip = divide(data.priceVip)
      this.product.stock = data.stock
      this.product.weight = data.weight
      this.product.freightFlag = data.freightFlag
      this.product.freightId = data.freightId

      if (data.productCommissions.length > 0) {
        this.product.productCommissions = data.productCommissions
        this.product.productCommissions.forEach((item) => {
          item.rate = divide(item.rate)
        })
      }
      if (data.listSku.length > 0) {
        this.product.listSku = data.listSku
        this.handdleSku(data.listSku)
      }
    },
    async getCategory () {
      this.frontCategoryList = await this.getCategoryList(1)
      this.backCategoryList = await this.getCategoryList(2)
    },
    async getFreightList () {
      let { data } = await getTemplateList()
      this.freightList = data.dataList
    },
    async getCategoryList (categorytype) {
      let { data } = await getListCategory({
        categorytype,
        pageNum: '',
        pageSize: ''
      })
      return data
    },
    multiplySpecs (specs) {
      var curSkus = []
      specs.forEach((spec, specIndex, totalSpecs) => {
        var tempSpecSku = []
        spec.values.forEach((attr, attrIndex, attrsInSpec) => {
          const appendingValue = {
            specCn: spec.nameCn,
            specEn: spec.nameEn,
            attrCn: attr.nameCn,
            attrEn: attr.nameEn,
            pid: spec.pid,
            vid: attr.vid
          }
          if (specIndex === 0) {
            const appendingCombination = []
            appendingCombination.push(appendingValue) // []
            curSkus.push(appendingCombination) // [[]]
          } else {
            var tempCombinations = []
            curSkus.forEach((combination, combinationIndex) => {
              const appendingCombination = combination.concat([appendingValue]) // []
              tempCombinations = tempCombinations.concat([ // [[]]
                appendingCombination
              ])
            })
            tempSpecSku = tempSpecSku.concat(tempCombinations) // [[]]
          }
        })
        if (specIndex !== 0) {
          curSkus = tempSpecSku
        }
      })
      console.log('curSkus', curSkus)
      return curSkus
    },
    getSkuAttribute (skuValueMaps, specCn) {
      var i
      skuValueMaps.forEach((item, index) => {
        if (item.specCn === specCn) {
          i = index
        }
      })
      return `${skuValueMaps[i].attrCn}/${skuValueMaps[i].attrEn}`
    },
    setDivide () {
      this.product.price = divide(this.product.price)
      this.product.priceVip = divide(this.product.priceVip)
      this.product.listSku = this.formattedSkus
      this.product.listSku.forEach((item) => {
        item.price = divide(item.price)
        item.priceVip = divide(item.priceVip)
      })
      this.product.productCommissions.forEach((item) => {
        item.rate = divide(item.rate)
      })
    },
    async saveProduct () {
      // 价格*100
      this.product.price = multiply(this.product.price)
      this.product.priceVip = multiply(this.product.priceVip)
      this.product.listSku = this.formattedSkus

      this.product.listSku.forEach((item) => {
        item.price = multiply(item.price)
        item.priceVip = multiply(item.priceVip)
      })
      this.product.productCommissions.forEach((item) => {
        item.rate = multiply(item.rate)
      })
      if (this.product.id) {
        await updateProduct(this.product).catch(() => {
          // 还原 除100
          this.setDivide()
          this.saveDisabled = false
          return false
        })
        this.$router.back()
      } else {
        await insertProduct(this.product).catch(() => {
          this.setDivide()
          this.saveDisabled = false
          return false
        })
        this.$router.back()
      }
    },
    clickTab (index) {
      this.tabActive = index
    },
    getWeightTemplateType () {
      let templateType = 0
      this.freightList.some((item) => {
        if (item.id === this.product.freightId) {
          templateType = item.templateType
          return true
        }
      })
      return templateType
    },
    clickToSave () {
      if (this.product.freightFlag === 2) {
        if (!this.product.freightId) {
          this.$message({
            type: 'warning',
            message: '请选择运费模板'
          })
          return
        }
        if (this.getWeightTemplateType() === 1 && !this.product.weight) {
          this.$message({
            type: 'warning',
            message: '请填写重量'
          })
          return
        }
      }
      let flag = 0
      this.product.productCommissions.some((item) => {
        if (isNaN(item.rate) || item.rate === '' || item.rate === undefined || item.rate < 0 || item.rate > 9999999) {
          flag = 1
          return true
        }
      })

      if (flag) {
        this.$message({
          type: 'warning',
          message: '请填写正确的商品返利比例'
        })
        return
      }

      this.product.productsFormCn = arrayToString(this.upload.productsFormCn)
      this.product.productsFormEn = arrayToString(this.upload.productsFormEn)
      this.product.productsRotationCn = arrayToString(this.upload.productsRotationCn)
      this.product.productsRotationEn = arrayToString(this.upload.productsRotationEn)
      this.product.productsDetailCn = arrayToString(this.upload.productsDetailCn)
      this.product.productsDetailEn = arrayToString(this.upload.productsDetailEn)
      if (this.upload.productsRotationCn.length > 0) {
        this.product.coverCn = this.upload.productsRotationCn[0].url
      }
      if (this.upload.productsRotationEn.length > 0) {
        this.product.coverEn = this.upload.productsRotationEn[0].url
      }

      this.$refs['product'].validate((valid) => {
        if (valid) {
          this.saveDisabled = true
          this.saveProduct()
        } else {
          this.$message({
            type: 'warning',
            message: '请填写完整'
          })
          return false
        }
      })
    },
    clickToCancel () {
      this.$router.back()
    },
    clickToAddSpec () {
      if (this.skuProps.length >= 3) {
        this.$message({
          message: '最多允许添加3组规格值',
          type: 'warning'
        })
        return
      }
      this.$refs['attributesFrom'].validate((valid) => {
        if (valid) {
          const newSpec = {
            pid: null,
            nameCn: this.attributesFrom.inputingSpecNameCn,
            nameEn: this.attributesFrom.inputingSpecNameEn,
            values: []
          }
          this.skuProps.push(newSpec)
          this.clickToCancelAddSpec()
        } else {
          return false
        }
      })
    },
    clickToCancelAddSpec () {
      this.attributesFrom.inputingSpecNameCn = ''
      this.attributesFrom.inputingSpecNameEn = ''
      this.$nextTick(() => {
        this.$refs['attributesFrom'].clearValidate()
      })
    },
    clickToDeleteSku (index, row) {
      this.skuProps.splice(index, 1)
    },
    // 商品规格 Tags 相关方法
    clickToRemoveAttribute (attrIndex, specIndex) {
      this.skuProps[specIndex].values.splice(attrIndex, 1)
    },
    clickToShowTagInput (specIndex) {
      this.tagInputValueCn = ''
      this.tagInputValueEn = ''
      this.activeTag = specIndex
      this.tagInputVisible = true
    },
    handleOptionsFront (frontIdList) {
      this.product.category = frontIdList.map(value => {
        return { id: value }
      })
    },
    handleOptionsBack (backIdList) {
      this.product.categoryManager = {
        id: backIdList[1]
      }
    },
    handleUploaderRemove (file, fileList, activeUploader, index) {
      var mappedFileList = fileList.map((mappingfile) => {
        if (mappingfile.response !== undefined) {
          mappingfile.url = mappingfile.response.data
          return mappingfile
        } else {
          return mappingfile
        }
      })
      if (activeUploader === 'productsFormCn') {
        this.upload.productsFormCn = fileList
      } else if (activeUploader === 'productsFormEn') {
        this.upload.productsFormEn = fileList
      } else if (activeUploader === 'swiperCn') {
        this.upload.productsRotationCn = fileList
      } else if (activeUploader === 'swiperEn') {
        this.upload.productsRotationEn = fileList
      } else if (activeUploader === 'detailCn') {
        this.upload.productsDetailCn = fileList
      } else if (activeUploader === 'detailEn') {
        this.upload.productsDetailEn = fileList
      }
      if (activeUploader === 'skuUploader') {
        this.tempProduct.goodsSku[index].fileList = mappedFileList
        this.tempProduct.goodsSku[index].image = ''
      }
    },
    // 商品图片上传成功
    handleUploadSuccess (response, file, fileList, type) {
      var mappedFileList = fileList.map((mappingfile) => {
        if (mappingfile.response !== undefined) {
          mappingfile.url = mappingfile.response.data
          return mappingfile
        } else {
          return mappingfile
        }
      })

      if (type === 'productsFormCn') {
        this.upload.productsFormCn[0] = { url: response.data }
      } else if (type === 'productsFormEn') {
        this.upload.productsFormEn[0] = { url: response.data }
      } else if (type === 'swiperCn') {
        this.upload.productsRotationCn = mappedFileList
        // this.upload.productsRotationCn.push({ url: response.data })
      } else if (type === 'swiperEn') {
        this.upload.productsRotationEn = mappedFileList
        // this.upload.productsRotationEn.push({ url: response.data })
      } else if (type === 'detailCn') {
        this.upload.productsDetailCn = mappedFileList
      } else if (type === 'detailEn') {
        this.upload.productsDetailEn = mappedFileList
      }
    },
    handleUploaderSuccess (response, file, fileList, activeUploader, index) {
      var mappedFileList = fileList.map((mappingfile) => {
        if (mappingfile.response !== undefined) {
          mappingfile.url = mappingfile.response.data
          return mappingfile
        } else {
          return mappingfile
        }
      })
      if (activeUploader === 'skuUploader') {
        this.product.listSku[index].fileList = mappedFileList
        this.product.listSku[index].cover = response.data
      }
    },
    // 上传文件前  对文件类型进行判断
    handleBeforeUpload (file, uploadStatus) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      // 商品图片格式判断
      if (!isLt2M) {
        Message.error('上传图片大小必须小于2M')
        return false
      }
      if (!isIMAGE) {
        Message.error('只能上传jpg，jpeg，png格式的图片')
        return false
      }
    },
    handleConfirmTagInput (specIndex) {
      if (this.skuProps[specIndex].values.length >= 5) {
        this.$message({
          message: '最多允许添加5组规格属性值',
          type: 'warning'
        })
        return
      }
      this.$refs['specFrom'].validate((valid) => {
        if (valid) {
          const attribute = {
            vid: null,
            nameCn: this.specFrom.tagInputValueCn,
            nameEn: this.specFrom.tagInputValueEn,
            image: null
          }
          this.skuProps[specIndex].values.push(attribute)
          this.tagInputVisible = false
          this.specFrom.tagInputValueCn = ''
          this.specFrom.tagInputValueEn = ''
        } else {
          return false
        }
      })
    },
    handdleSku (data) {
      let specificationsCn = Object.keys(JSON.parse(data[0].valuesCn))
      let specificationsEn = Object.keys(JSON.parse(data[0].valuesEn))

      specificationsCn.forEach((item, index) => {
        this.skuProps.push({
          pid: null,
          nameCn: item,
          nameEn: specificationsEn[index],
          values: []
        })
      })

      // 得到所有组合
      var arrary = []
      data.forEach(item => {
        item.valuesJsonCn = JSON.parse(item.valuesCn)
        item.valuesJsonEn = JSON.parse(item.valuesEn)
        let keysEn = Object.keys(item.valuesJsonEn)
        let i = 0
        for (let key in item.valuesJsonCn) {
          let obj = {}
          obj.skuNameCn = key // name 颜色
          obj.specificationsCn = item.valuesJsonCn[key] // value 红

          obj.skuNameEn = keysEn[i] // name 颜色
          obj.specificationsEn = item.valuesJsonEn[keysEn[i]] // value 红
          arrary.push(JSON.stringify(obj))
          i++
        }
      })
      // 去重
      let arraryNoRepeat = new Set(arrary)
      // 赋值
      for (let item of arraryNoRepeat) {
        let obj = JSON.parse(item)
        this.skuProps.forEach(value => {
          if (value.nameCn === obj.skuNameCn) {
            let skuObj = {}
            skuObj.nameCn = obj.specificationsCn
            skuObj.nameEn = obj.specificationsEn
            value.values.push(skuObj)
          }
        })
      }

      // console.log('skuProps', this.skuProps)
      // console.log('formattedSkus', this.formattedSkus)

      // this.formattedSkus.forEach((formattedSku, index) => {
      //   formattedSku.id = data[index].id
      //   formattedSku.productsId = data[index].productsId
      //   formattedSku.price = data[index].price
      //   formattedSku.priceVip = data[index].priceVip
      //   formattedSku.stock = data[index].stock
      //   formattedSku.image = data[index].image
      //   formattedSku.fileList = [
      //     {
      //       name: '',
      //       url: data[index].image
      //     }
      //   ]
      // })
    }
  }
}
</script>

<style scoped lang="less">
.pageTitle {
  font-size: 20px;
  color: black;
  font-weight: bold;
}
.filter-container {
  height: 50px;
}
// .filterButtons {
//   float: right;
// }
.form {
  width: 100%;
}
.verticalRadioItem {
  margin: 20px 20px;
  width: 100%;
  height: 30px;
}
.verticalButton {
  margin-left: 10px;
}
.normalOperatorBox {
  width: 30%;
  min-width: 100px;
}
.avatar-uploader {
  // display: inline-block;
  width: 148px;
  height: 148px;
  overflow: hidden;
}
.recommendProduct{
  border:1px solid #ebebeb;
  border-radius:4px;
  width:50%;
  padding-left:20px;
  .checkGroup{
    border:1px solid #ebebeb;
    padding-left:20px;
  }
}
.districtManage{
  background:white;
  margin-top:10px;
  border:1px solid #ebebeb;
  .title{
    padding-left:18px;
    font-size: 16px;
    line-height: 60px;
    font-weight: 600;
    padding-right:20px;
    display: flex;
    justify-content: space-between;
    margin:0;
    .showAll{
      cursor: pointer;
    }
  }
  .showDistrict{
    width:100%;
    height:400px;
    margin:0 auto;
    margin-bottom:20px;
    overflow: auto;
    .chooseTitle{
      text-align: center;
      line-height:45px;
      margin:0;
      .chooseAll{
        margin-left:18px;
        float:left;
      }
      .confimButton{
        float:right;
      }
    }
    .chooseDistrict{
      width:100%;
      line-height:40px;
      .directly{
        display: flex;
        span{
          display: inline-block;
          width:25%;
          border:1px solid #ebebeb;
          padding-left:18px;
        }
      }
      .otherDirectly{
        padding:0;
        li{
          border:1px solid #ebebeb;
          padding-left:18px;
          list-style: none;
        }
      }
    }
  }
}
.input-new-tag {
  margin-right: 5px;
  // width: calc((100% - 70px)/2);
}
.tabs {
  width: 60%;
  text-align: center;
  margin: 10px auto;
  background: #f8f4f3;
  span {
    width: 50%;
    display: inline-block;
    padding: 5px;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
  }
  .active {
    background: #fde3de;
  }
}
.title {
  display: inline-block;
  width: 30%;
  text-align: left;
  margin-left: 20px;
}

.draggable {
  // float: left;
  position: absolute;
  top: 0;
}
.draggable__item {
  width:148px;
  height:148px;
  margin-right:8px;
  display: inline-block;
  opacity: .4;
  cursor: pointer;
}
</style>
